"""
后端温度分析服务
独立于GUI的核心分析引擎，支持视频流处理和区域温度分析
为API接口提供核心功能支持
"""

import cv2
import numpy as np
import threading
import time
from typing import List, Dict, Any, Optional, Tuple, Callable
import logging
from dataclasses import dataclass

from ..core.temperature_mapper import TemperatureMapper
from ..core.video_stream import VideoStreamManager, validate_stream_url
from ..core.data_storage import DataStorage
from ..utils.utils import success_response, error_response, ResponseCode


@dataclass
class RegionCoordinate:
    """区域坐标数据类"""
    x1: int
    y1: int
    x2: int
    y2: int
    
    @property
    def width(self) -> int:
        return self.x2 - self.x1
        
    @property
    def height(self) -> int:
        return self.y2 - self.y1


@dataclass
class TemperatureStats:
    """温度统计数据类"""
    min_temp: float
    max_temp: float
    avg_temp: float
    temp_diff: float
    min_pos: Tuple[int, int]
    max_pos: Tuple[int, int]
    pixel_count: int


class ThermalService:
    """热成像温度分析服务核心类"""
    
    def __init__(self, data_storage: Optional[DataStorage] = None, auto_load_calibration: bool = True):
        """
        初始化温度分析服务
        
        Args:
            data_storage: 数据存储实例，如果未提供则创建默认实例
            auto_load_calibration: 是否自动加载最新的标定点文件
        """
        self.temp_mapper = TemperatureMapper()
        self.data_storage = data_storage or DataStorage()
        
        # 视频流管理
        self.stream_manager = VideoStreamManager()
        self.current_frame = None
        self.current_frame_hsv = None
        self.is_streaming = False
        self.stream_lock = threading.Lock()
        
        # 静态图片处理
        self.current_image = None
        self.current_image_hsv = None
        
        # 分析状态
        self.last_analysis_time = None
        self.analysis_callbacks: List[Callable] = []
        
        # 日志配置
        logging.basicConfig(level=logging.INFO)
        self.logger = logging.getLogger(__name__)
        
        # 设置回调函数
        self._setup_stream_callbacks()
        
        # 自动加载最新的标定点
        if auto_load_calibration:
            self.load_calibration_points()
        
    def _setup_stream_callbacks(self):
        """设置视频流回调函数"""
        self.stream_manager.frame_callback = self._on_frame_received
        self.stream_manager.status_callback = self._on_stream_status_changed
        self.stream_manager.error_callback = self._on_stream_error
        
    def _on_frame_received(self, frame_bgr: np.ndarray, frame_hsv: np.ndarray):
        """处理接收到的视频帧"""
        with self.stream_lock:
            self.current_frame = frame_bgr.copy()
            self.current_frame_hsv = frame_hsv.copy()
            self.last_analysis_time = time.time()
            
        # 触发分析回调
        for callback in self.analysis_callbacks:
            try:
                callback(frame_bgr, frame_hsv)
            except Exception as e:
                self.logger.error(f"分析回调执行失败: {e}")
                
    def _on_stream_status_changed(self, status: str):
        """处理流状态变化"""
        self.logger.info(f"视频流状态: {status}")
        
    def _on_stream_error(self, error: str):
        """处理流错误"""
        self.logger.error(f"视频流错误: {error}")
        
    def start_stream_analysis(self, stream_url: str, fps_limit: int = 10, frame_skip: int = 1) -> Dict[str, Any]:
        """
        开始视频流温度分析
        
        Args:
            stream_url: 视频流地址 (RTSP/RTMP)
            fps_limit: 帧率限制
            frame_skip: 帧跳跃数
            
        Returns:
            操作结果字典
        """
        try:
            # 验证流地址
            if not validate_stream_url(stream_url):
                return error_response(
                    message='不支持的流地址格式，仅支持RTSP和RTMP协议',
                    data={'stream_url': stream_url}
                )
                
            # 启动流 (start_stream方法内部会设置URL和其他参数)
            success = self.stream_manager.start_stream(stream_url, fps_limit, frame_skip)
            
            if success:
                self.is_streaming = True
                self.logger.info(f"成功启动视频流分析: {stream_url}")
                return success_response(
                    message='视频流连接成功，开始温度分析',
                    data={
                        'stream_url': stream_url,
                        'protocol': self.stream_manager.get_protocol(),
                        'fps_limit': fps_limit,
                        'frame_skip': frame_skip
                    }
                )
            else:
                return error_response(
                    message='无法连接到视频流',
                    data={'stream_url': stream_url}
                )
                
        except Exception as e:
            self.logger.error(f"启动视频流分析失败: {e}")
            return error_response(
                message=f'启动视频流失败: {str(e)}',
                code=ResponseCode.INTERNAL_ERROR,
                data={'stream_url': stream_url}
            )
            
    def stop_stream_analysis(self) -> Dict[str, Any]:
        """
        停止视频流温度分析
        
        Returns:
            操作结果字典
        """
        try:
            self.stream_manager.stop_stream()
            self.is_streaming = False
            
            with self.stream_lock:
                self.current_frame = None
                self.current_frame_hsv = None
                
            self.logger.info("视频流温度分析已停止")
            return {
                'success': True,
                'message': '视频流分析已停止'
            }
            
        except Exception as e:
            self.logger.error(f"停止视频流分析失败: {e}")
            return {
                'success': False,
                'message': f'停止视频流失败: {str(e)}'
            }
            
    def analyze_regions(self, regions: List[Dict[str, int]], 
                       save_result: bool = False,
                       image_source: str = "stream") -> Dict[str, Any]:
        """
        分析指定区域的温度分布
        
        Args:
            regions: 区域列表，每个区域包含 x1, y1, x2, y2 坐标
            save_result: 是否保存分析结果
            image_source: 图像来源描述
            
        Returns:
            分析结果字典
        """
        try:
            # 检查是否有可用的图像数据
            with self.stream_lock:
                if self.current_frame_hsv is None:
                    return {
                        'success': False,
                        'message': '没有可用的图像数据，请确保视频流正在运行或已加载图像',
                        'regions': []
                    }
                
                # 使用当前帧数据
                frame_hsv = self.current_frame_hsv.copy()
                frame_bgr = self.current_frame.copy() if self.current_frame is not None else None
                
            height, width = frame_hsv.shape[:2]
            
            # 验证区域坐标
            valid_regions = []
            for region_data in regions:
                try:
                    region = RegionCoordinate(
                        x1=max(0, min(region_data['x1'], width-1)),
                        y1=max(0, min(region_data['y1'], height-1)),
                        x2=max(0, min(region_data['x2'], width)),
                        y2=max(0, min(region_data['y2'], height))
                    )
                    
                    if region.width > 0 and region.height > 0:
                        valid_regions.append(region)
                    else:
                        self.logger.warning(f"跳过无效区域: {region_data}")
                        
                except (KeyError, TypeError, ValueError) as e:
                    self.logger.warning(f"跳过格式错误的区域: {region_data}, 错误: {e}")
                    continue
                    
            if not valid_regions:
                return {
                    'success': False,
                    'message': '没有有效的分析区域',
                    'regions': []
                }
                
            # 分析每个区域
            region_results = []
            for i, region in enumerate(valid_regions):
                stats = self._analyze_region_temperature(frame_hsv, region)
                
                region_result = {
                    'region_id': i + 1,
                    'coordinates': {
                        'x1': region.x1,
                        'y1': region.y1,
                        'x2': region.x2,
                        'y2': region.y2
                    },
                    'size': {
                        'width': region.width,
                        'height': region.height
                    },
                    'temperature_stats': {
                        'min_temp': stats.min_temp,
                        'max_temp': stats.max_temp,
                        'avg_temp': stats.avg_temp,
                        'temp_diff': stats.temp_diff,
                        'min_position': {
                            'x': stats.min_pos[0],
                            'y': stats.min_pos[1]
                        },
                        'max_position': {
                            'x': stats.max_pos[0],
                            'y': stats.max_pos[1]
                        },
                        'pixel_count': stats.pixel_count
                    }
                }
                region_results.append(region_result)
                
            # 计算整体统计
            global_stats = self._calculate_global_stats(region_results) if region_results else None
            
            result = {
                'success': True,
                'message': f'成功分析{len(region_results)}个区域',
                'analysis_time': time.strftime('%Y-%m-%d %H:%M:%S'),
                'image_info': {
                    'width': width,
                    'height': height,
                    'source': image_source
                },
                'regions': region_results,
                'global_stats': global_stats
            }
            
            # 保存分析结果
            if save_result and region_results:
                try:
                    # 构造保存数据格式
                    save_data = {
                        'image_info': result['image_info'],
                        'global_stats': global_stats,
                        'regions': []
                    }
                    
                    for region_result in region_results:
                        coords = region_result['coordinates']
                        stats = region_result['temperature_stats']
                        
                        save_data['regions'].append({
                            'x1': coords['x1'],
                            'y1': coords['y1'],
                            'x2': coords['x2'],
                            'y2': coords['y2'],
                            'width': region_result['size']['width'],
                            'height': region_result['size']['height'],
                            'stats': {
                                'min_temp': stats['min_temp'],
                                'max_temp': stats['max_temp'],
                                'avg_temp': stats['avg_temp'],
                                'temp_diff': stats['temp_diff'],
                                'min_pos': (stats['min_position']['x'], stats['min_position']['y']),
                                'max_pos': (stats['max_position']['x'], stats['max_position']['y']),
                                'pixel_count': stats['pixel_count']
                            }
                        })
                    
                    file_path = self.data_storage.save_analysis_result(save_data)
                    result['saved_file'] = file_path
                    self.logger.info(f"分析结果已保存到: {file_path}")
                    
                except Exception as e:
                    self.logger.error(f"保存分析结果失败: {e}")
                    result['save_error'] = str(e)
                    
            return result
            
        except Exception as e:
            self.logger.error(f"区域温度分析失败: {e}")
            return {
                'success': False,
                'message': f'分析失败: {str(e)}',
                'regions': []
            }
            
    def analyze_image_regions(self, image: np.ndarray, regions: List[Dict[str, int]], 
                             save_result: bool = False,
                             image_source: str = "image_upload") -> Dict[str, Any]:
        """
        分析静态图片中指定区域的温度分布
        
        Args:
            image: BGR格式的图像数据 (OpenCV格式)
            regions: 区域列表，每个区域包含 x1, y1, x2, y2 坐标
            save_result: 是否保存分析结果
            image_source: 图像来源描述
            
        Returns:
            分析结果字典
        """
        try:
            # 验证图像数据
            if image is None or image.size == 0:
                return {
                    'success': False,
                    'message': '图像数据无效或为空',
                    'regions': []
                }
                
            # 转换为HSV格式进行温度分析
            frame_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
            height, width = frame_hsv.shape[:2]
            
            # 保存当前图片数据用于标定
            self.current_image = image.copy()
            self.current_image_hsv = frame_hsv.copy()
            
            # 检查当前标定点状态
            calibration_info = self.temp_mapper.get_calibration_info()
            calibration_count = len(calibration_info)
            
            self.logger.info(f"开始分析图片，尺寸: {width}x{height}，区域数: {len(regions)}")
            self.logger.info(f"标定点状态: {calibration_count} 个标定点")
            
            if calibration_count >= 2:
                self.logger.info("将使用标定点插值进行温度计算")
                for i, point in enumerate(calibration_info):
                    self.logger.info(f"  标定点 {i+1}: 位置{point['position']} -> 温度{point['temperature']}°C")
            else:
                self.logger.info("标定点不足，将使用默认温度映射")
            
            # 验证区域坐标
            valid_regions = []
            for region_data in regions:
                try:
                    region = RegionCoordinate(
                        x1=max(0, min(region_data['x1'], width-1)),
                        y1=max(0, min(region_data['y1'], height-1)),
                        x2=max(0, min(region_data['x2'], width)),
                        y2=max(0, min(region_data['y2'], height))
                    )
                    
                    if region.width > 0 and region.height > 0:
                        valid_regions.append(region)
                    else:
                        self.logger.warning(f"跳过无效区域: {region_data}")
                        
                except (KeyError, TypeError, ValueError) as e:
                    self.logger.warning(f"跳过格式错误的区域: {region_data}, 错误: {e}")
                    continue
                    
            if not valid_regions:
                return {
                    'success': False,
                    'message': '没有有效的分析区域',
                    'regions': []
                }
                
            # 分析每个区域
            region_results = []
            for i, region in enumerate(valid_regions):
                stats = self._analyze_region_temperature(frame_hsv, region)
                
                region_result = {
                    'region_id': i + 1,
                    'coordinates': {
                        'x1': region.x1,
                        'y1': region.y1,
                        'x2': region.x2,
                        'y2': region.y2
                    },
                    'size': {
                        'width': region.width,
                        'height': region.height
                    },
                    'temperature_stats': {
                        'min_temp': stats.min_temp,
                        'max_temp': stats.max_temp,
                        'avg_temp': stats.avg_temp,
                        'temp_diff': stats.temp_diff,
                        'min_position': {
                            'x': stats.min_pos[0],
                            'y': stats.min_pos[1]
                        },
                        'max_position': {
                            'x': stats.max_pos[0],
                            'y': stats.max_pos[1]
                        },
                        'pixel_count': stats.pixel_count
                    }
                }
                region_results.append(region_result)
                
            # 计算整体统计
            global_stats = self._calculate_global_stats(region_results) if region_results else None
            
            result = {
                'success': True,
                'message': f'成功分析{len(region_results)}个区域',
                'analysis_time': time.strftime('%Y-%m-%d %H:%M:%S'),
                'data': {
                    'image_info': {
                        'width': width,
                        'height': height,
                        'source': image_source
                    },
                    'global_stats': global_stats,
                    'total_regions': len(region_results)
                },
                'regions': region_results
            }
            
            # 保存分析结果
            if save_result and region_results:
                try:
                    # 构造保存数据格式
                    save_data = {
                        'image_info': result['data']['image_info'],
                        'global_stats': global_stats,
                        'regions': []
                    }
                    
                    for region_result in region_results:
                        coords = region_result['coordinates']
                        stats = region_result['temperature_stats']
                        
                        save_data['regions'].append({
                            'x1': coords['x1'],
                            'y1': coords['y1'],
                            'x2': coords['x2'],
                            'y2': coords['y2'],
                            'width': region_result['size']['width'],
                            'height': region_result['size']['height'],
                            'stats': {
                                'min_temp': stats['min_temp'],
                                'max_temp': stats['max_temp'],
                                'avg_temp': stats['avg_temp'],
                                'temp_diff': stats['temp_diff'],
                                'min_pos': (stats['min_position']['x'], stats['min_position']['y']),
                                'max_pos': (stats['max_position']['x'], stats['max_position']['y']),
                                'pixel_count': stats['pixel_count']
                            }
                        })
                    
                    file_path = self.data_storage.save_analysis_result(save_data)
                    result['data']['saved_file'] = file_path
                    self.logger.info(f"图片分析结果已保存到: {file_path}")
                    
                except Exception as e:
                    self.logger.error(f"保存图片分析结果失败: {e}")
                    result['data']['save_error'] = str(e)
                    
            self.logger.info(f"图片温度分析完成，成功分析{len(region_results)}个区域")
            return result
            
        except Exception as e:
            self.logger.error(f"图片温度分析失败: {e}")
            return {
                'success': False,
                'message': f'图片分析失败: {str(e)}',
                'regions': []
            }
            
    def _analyze_region_temperature(self, frame_hsv: np.ndarray, region: RegionCoordinate) -> TemperatureStats:
        """
        分析单个区域的温度统计
        
        Args:
            frame_hsv: HSV格式的图像帧
            region: 区域坐标
            
        Returns:
            温度统计结果
        """
        # 检查标定点状态
        calibration_count = len(self.temp_mapper.calibration_points)
        self.logger.info(f"区域温度分析开始 - 当前标定点数量: {calibration_count}")
        
        # 提取区域温度数据
        temperature_data = []  # [(温度, x, y), ...]
        
        for y in range(region.y1, region.y2):
            for x in range(region.x1, region.x2):
                if 0 <= x < frame_hsv.shape[1] and 0 <= y < frame_hsv.shape[0]:
                    hsv_color = frame_hsv[y, x]
                    temp = self.temp_mapper.color_to_temperature(hsv_color)
                    temperature_data.append((temp, x, y))
                    
        if not temperature_data:
            # 处理空区域情况
            return TemperatureStats(
                min_temp=0.0, max_temp=0.0, avg_temp=0.0, temp_diff=0.0,
                min_pos=(region.x1, region.y1), max_pos=(region.x1, region.y1),
                pixel_count=0
            )
            
        # 计算统计信息
        temperature_data.sort(key=lambda item: item[0])
        
        min_data = temperature_data[0]
        max_data = temperature_data[-1]
        
        min_temp = min_data[0]
        max_temp = max_data[0]
        avg_temp = sum(item[0] for item in temperature_data) / len(temperature_data)
        temp_diff = max_temp - min_temp
        
        return TemperatureStats(
            min_temp=min_temp,
            max_temp=max_temp,
            avg_temp=avg_temp,
            temp_diff=temp_diff,
            min_pos=(min_data[1], min_data[2]),
            max_pos=(max_data[1], max_data[2]),
            pixel_count=len(temperature_data)
        )
        
    def _calculate_global_stats(self, region_results: List[Dict]) -> Dict[str, Any]:
        """
        计算所有区域的全局统计信息
        
        Args:
            region_results: 区域分析结果列表
            
        Returns:
            全局统计信息
        """
        if not region_results:
            return {}
            
        all_min_temps = [r['temperature_stats']['min_temp'] for r in region_results]
        all_max_temps = [r['temperature_stats']['max_temp'] for r in region_results]
        all_avg_temps = [r['temperature_stats']['avg_temp'] for r in region_results]
        
        global_min_temp = min(all_min_temps)
        global_max_temp = max(all_max_temps)
        global_avg_temp = sum(all_avg_temps) / len(all_avg_temps)
        
        # 找到全局极值对应的位置
        min_region = next(r for r in region_results 
                         if r['temperature_stats']['min_temp'] == global_min_temp)
        max_region = next(r for r in region_results 
                         if r['temperature_stats']['max_temp'] == global_max_temp)
        
        return {
            'min_temp': global_min_temp,
            'max_temp': global_max_temp,
            'avg_temp': global_avg_temp,
            'temp_diff': global_max_temp - global_min_temp,
            'min_pos': (
                min_region['temperature_stats']['min_position']['x'],
                min_region['temperature_stats']['min_position']['y']
            ),
            'max_pos': (
                max_region['temperature_stats']['max_position']['x'],
                max_region['temperature_stats']['max_position']['y']
            ),
            'total_regions': len(region_results)
        }
        
    def get_stream_status(self) -> Dict[str, Any]:
        """
        获取视频流状态信息
        
        Returns:
            流状态字典
        """
        with self.stream_lock:
            return {
                'is_streaming': self.is_streaming,
                'has_current_frame': self.current_frame is not None,
                'last_analysis_time': self.last_analysis_time,
                'stream_url': self.stream_manager.get_stream_url() if hasattr(self.stream_manager, 'get_stream_url') else None,
                'protocol': self.stream_manager.get_protocol() if hasattr(self.stream_manager, 'get_protocol') else None
            }
            
    def add_analysis_callback(self, callback: Callable[[np.ndarray, np.ndarray], None]):
        """
        添加实时分析回调函数
        
        Args:
            callback: 回调函数，接收BGR和HSV帧参数
        """
        self.analysis_callbacks.append(callback)
        
    def remove_analysis_callback(self, callback: Callable):
        """
        移除分析回调函数
        
        Args:
            callback: 要移除的回调函数
        """
        if callback in self.analysis_callbacks:
            self.analysis_callbacks.remove(callback)
            
    def set_temperature_mapper(self, mapper: TemperatureMapper):
        """
        设置温度映射器
        
        Args:
            mapper: 温度映射器实例
        """
        self.temp_mapper = mapper
        
    def get_temperature_mapper(self) -> TemperatureMapper:
        """
        获取当前温度映射器
        
        Returns:
            当前的温度映射器实例
        """
        return self.temp_mapper
        
    def add_calibration_point(self, x: int, y: int, temperature: float, auto_save: bool = True) -> bool:
        """
        添加标定点
        
        Args:
            x: X坐标
            y: Y坐标 
            temperature: 参考温度
            auto_save: 是否自动保存到文件
            
        Returns:
            是否添加成功
        """
        try:
            # 优先使用当前图片数据，其次使用视频流数据
            hsv_data = self.current_image_hsv if self.current_image_hsv is not None else self.current_frame_hsv
            
            if hsv_data is None:
                self.logger.warning("无图片或帧数据，无法添加标定点")
                return False
                
            # 检查坐标是否有效
            height, width = hsv_data.shape[:2]
            if x < 0 or x >= width or y < 0 or y >= height:
                self.logger.warning(f"坐标超出范围: ({x}, {y}), 图片尺寸: {width}x{height}")
                return False
                
            # 获取HSV颜色值
            hsv_color = hsv_data[y, x]
            
            # 添加到温度映射器
            self.temp_mapper.add_calibration_point(hsv_color, temperature, (x, y))
            
            # 自动保存标定点到文件
            if auto_save:
                self.save_calibration_points()
            
            self.logger.info(f"标定点添加成功: ({x}, {y}) -> {temperature}°C")
            return True
            
        except Exception as e:
            self.logger.error(f"添加标定点失败: {e}")
            return False
            
    def get_calibration_points(self):
        """获取所有标定点信息"""
        try:
            from ..gui.thermal_analyzer_service import CalibrationPoint
            calibration_info = self.temp_mapper.get_calibration_info()
            points = []
            
            for i, point_info in enumerate(calibration_info):
                # 添加调试日志
                self.logger.debug(f"处理标定点 {i}: {point_info}")
                
                point = CalibrationPoint(
                    position=point_info['position'],
                    hsv_color=point_info['hsv'],
                    temperature=point_info['temperature'],
                    index=i
                )
                points.append(point)
                
            return points
        except Exception as e:
            self.logger.error(f"获取标定点失败: {e}")
            # 添加详细错误信息
            calibration_info = self.temp_mapper.get_calibration_info()
            self.logger.error(f"标定点原始数据: {calibration_info}")
            return []
            
    def clear_calibration_points(self, auto_save: bool = True):
        """清空所有标定点"""
        try:
            self.temp_mapper.clear_calibration_points()
            
            # 自动保存空的标定点列表到文件
            if auto_save:
                self.save_calibration_points()
            
            self.logger.info("所有标定点已清空")
            return True
        except Exception as e:
            self.logger.error(f"清空标定点失败: {e}")
            return False
            
    def remove_calibration_point(self, index: int, auto_save: bool = True) -> bool:
        """
        删除指定索引的标定点
        
        Args:
            index: 标定点索引 (0-based)
            auto_save: 是否自动保存到文件
            
        Returns:
            是否删除成功
        """
        try:
            # 添加删除前的状态日志
            calibration_info = self.temp_mapper.get_calibration_info()
            self.logger.info(f"删除前标定点状态: 共{len(calibration_info)}个标定点")
            self.logger.info(f"尝试删除索引 {index} 的标定点")
            
            success = self.temp_mapper.remove_calibration_point(index)
            
            if success:
                # 自动保存更新后的标定点列表到文件
                if auto_save:
                    self.save_calibration_points()
                
                self.logger.info(f"标定点 {index} 已删除")
                return True
            else:
                self.logger.warning(f"删除标定点失败: 无效的索引 {index}")
                return False
        except Exception as e:
            self.logger.error(f"删除标定点失败: {e}")
            # 添加调试信息
            import traceback
            self.logger.error(f"详细错误信息: {traceback.format_exc()}")
            return False
        
    def save_calibration_points(self) -> str:
        """
        保存标定点到固定文件 calibration.txt
        
        Returns:
            保存的文件路径
        """
        try:
            calibration_points = self.temp_mapper.get_calibration_info()
            file_path = self.data_storage.save_calibration_data(calibration_points)
            self.logger.info(f"标定点已保存到文件: {file_path}")
            return file_path
        except Exception as e:
            self.logger.error(f"保存标定点失败: {e}")
            raise
            
    def load_calibration_points(self, file_path: str = None) -> bool:
        """
        从固定文件 calibration.txt 加载标定点
        
        Args:
            file_path: 保留参数兼容性，始终从 calibration.txt 加载
            
        Returns:
            是否加载成功
        """
        try:
            # 始终从固定文件 calibration.txt 加载
            calibration_points = self.data_storage.load_default_calibration()
            if calibration_points:
                self.temp_mapper.clear_calibration_points()
                for point in calibration_points:
                    self.temp_mapper.add_calibration_point(
                        point['position'], 
                        point['hsv'], 
                        point['temperature']
                    )
                self.logger.info(f"成功加载 {len(calibration_points)} 个标定点从 calibration.txt")
                return True
            else:
                self.logger.info("calibration.txt 文件为空或不存在")
                return False
                
        except Exception as e:
            self.logger.error(f"加载标定点失败: {e}")
            return False
            
    def get_calibration_files(self) -> List[str]:
        """
        获取所有标定点文件列表
        
        Returns:
            标定点文件路径列表
        """
        try:
            import os
            import glob
            calibration_dir = self.data_storage.data_dir
            if os.path.exists(calibration_dir):
                # 查找标定点文件 (calibration*.txt)
                calibration_files = glob.glob(os.path.join(calibration_dir, "calibration*.txt"))
                # 按修改时间排序，最新的在前
                calibration_files.sort(key=os.path.getmtime, reverse=True)
                return calibration_files
            return []
        except Exception as e:
            self.logger.error(f"获取标定点文件列表失败: {e}")
            return []
    
    def cleanup(self):
        """清理资源"""
        if self.is_streaming:
            self.stop_stream_analysis()
        self.analysis_callbacks.clear()